import { defineStore } from 'pinia'
import { onMounted, ref } from 'vue'
import { NewLottery } from '@/models/NewLottery'
import { Prize } from '@/models/Prize'
import { LotteryDrawingStatus } from '@/enums/lottery'
import { getActivity, getAwardList, getPrize, type TGetActivityData } from '@/api'
import { useAppStore } from './app'
import { useToast } from 'vue-toastification'

export const useNewLotteryStore = defineStore('newlottery', () => {
  // 创建抽奖实例
  const lottery = ref(new NewLottery([]))
  const activity = ref<TGetActivityData>()
  const appStore = useAppStore()
  const toast = useToast()
  const awardMap = new Map<string, string>()

  onMounted(async () => {
    const { data } = await getActivity()
    activity.value = data.data
    const prizes = data.data.prize.map((v) => {
      awardMap.set(v.prize_name, v.prize_level)
      return new Prize(v.prize_id, v.prize_name, v.prize_level, v.prize_quantity, v.prize_image)
    })
    resetAll(prizes)
    updatePrizeInfo()
  })

  const allowMultipleDraws = ref(true)

  const updatePrizeInfo = async () => {
    const { data } = await getPrize(lottery.value.getCurrentPrize().getId())
    lottery.value.getCurrentPrize().setNumberOfWinners(data.data.awardnum)
    lottery.value.getCurrentPrize().setStock(data.data.prize_left)
    remainingAwardCount.value = data.data.unawardnum
    allowMultipleDraws.value = !['二等赏', '一等赏'].includes(data.data.prize_level)
    if (data.data.prize_level == '三等赏') {
      setDefaultDrawCount(1)
    } else {
      setDefaultDrawCount()
    }
  }

  const winners = ref<{ level: string; numbers: string[] }[]>([])

  const getWinners = async () => {
    const { data } = await getAwardList()
    winners.value = Object.entries(data.data).map(([key, value]) => {
      return { level: `${awardMap.get(key)}: ${key}`, numbers: value.map((v) => v.number) }
    })
  }

  // 生成号码池（380个不重复的号码）
  const generateTicketPool = () => {
    const tickets: string[] = []
    const usedNumbers = new Set<string>()

    while (tickets.length < 380) {
      const number = String(Math.floor(Math.random() * 900000) + 100000)
      if (!usedNumbers.has(number)) {
        tickets.push(number)
        usedNumbers.add(number)
      }
    }

    return tickets
  }

  // 初始化号码池
  lottery.value.setAvailableTickets(generateTicketPool())

  // 获取默认抽奖次数
  const getDefaultDrawCount = (remainingCount: number) => {
    if (remainingCount <= 0) return 0
    if (!allowMultipleDraws.value) return 1
    if (remainingCount < 10) return remainingCount
    return 10
  }

  // 设置默认抽奖次数
  const setDefaultDrawCount = (count?: number) => {
    const currentPrize = lottery.value.getCurrentPrize()
    const remainingCount = currentPrize.getStock()
    if (typeof count === 'number') {
      currentPrize.setNumberOfDraws(count)
    } else {
      currentPrize.setNumberOfDraws(getDefaultDrawCount(remainingCount))
    }
  }

  // 切换到上一个奖项
  const setPreviousPrizeLevelToCurrent = async () => {
    if (lottery.value.getDrawingStatus() !== LotteryDrawingStatus.NOT_STARTED) return
    await lottery.value.setPreviousPrize()
    setDefaultDrawCount()
    updatePrizeInfo()
  }

  // 切换到下一个奖项
  const setNextPrizeLevelToCurrent = async () => {
    if (lottery.value.getDrawingStatus() !== LotteryDrawingStatus.NOT_STARTED) return
    await lottery.value.setNextPrize()
    setDefaultDrawCount()
    updatePrizeInfo()
  }

  const remainingAwardCount = ref(0)

  // 开始抽奖
  const startDrawing = () => {
    const currentPrize = lottery.value.getCurrentPrize()
    const numberOfDraws = currentPrize.getNumberOfDraws()

    if (numberOfDraws <= 0) {
      toast.error('抽奖次数不足')
      return false
    }

    if (numberOfDraws > remainingAwardCount.value) {
      toast.error('剩余的未中奖人数不足')
      return false
    }

    appStore.switchAudio('LOTTERY_START')
    lottery.value.setDrawingStatus(LotteryDrawingStatus.IN_PROGRESS)
    return true
  }

  // 执行抽奖
  const draw = async () => {
    if (lottery.value.getDrawingStatus() !== LotteryDrawingStatus.IN_PROGRESS) {
      throw new Error('抽奖未开始')
    }

    const { list, remaining } = await lottery.value.draw()
    if (remaining !== -1) {
      remainingAwardCount.value = remaining
    }

    lottery.value.setDrawingStatus(LotteryDrawingStatus.COMPLETED)
    updatePrizeInfo()

    return list
  }

  // 重置所有数据
  const resetAll = (prizes: Prize[]) => {
    lottery.value = new NewLottery(prizes)
    lottery.value.setAvailableTickets(generateTicketPool())
  }

  // 获取当前奖项名称
  const getCurrentPrizeName = () => lottery.value.getCurrentPrize()?.getName() || ''

  const getCurrentPrizeLevel = () => lottery.value.getCurrentPrize()?.getPrizeLevel() || ''

  function resetDrawingStatus() {
    lottery.value.setDrawingStatus(LotteryDrawingStatus.NOT_STARTED)
  }

  return {
    lottery,
    setPreviousPrizeLevelToCurrent,
    setNextPrizeLevelToCurrent,
    startDrawing,
    draw,
    resetAll,
    getCurrentPrizeName,
    getCurrentPrizeLevel,
    winners,
    getWinners,
    resetDrawingStatus,
    allowMultipleDraws,
  }
})
